package com.lagou.utils;


import com.lagou.annotations.Component;

import java.sql.Connection;

@Component("connectionUtils")
public class ConnectionUtils {

    private ThreadLocal<Connection> threadLocal = new ThreadLocal<>();

    public Connection getCurrentThreadConnection() throws Exception {
        // 判断当前线程中是否绑定了数据库连接，如果没有的话需要获取一个连接并绑定到当前线程上
        Connection connection = threadLocal.get();
        if (connection == null) {
            connection = DruidUtils.getInstance().getConnection();
            // 绑定当前线程
            threadLocal.set(connection);
        }
        return connection;
    }
}
